﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Top.Web;
using Top.Web.Api;
using Top.Core;
using Top.Data;
using Top.PointStore.Business.Models;

namespace Top.PointStore.Business
{
    /// <summary> 系统使用的一些方法
    /// </summary>
    public static class SystemManager
    {
        /// <summary> 获取用户
        /// </summary>
        /// <param name="userid">用户id</param>
        /// <remarks>周子鉴 2015.01.24</remarks>
        public static async Task<S_Admin> GetAdmin(int userid)
        {
            if (userid <= 0)
            {
                return null;
            }
            const string sql = @"select * from s_admin where kid = {0} and F_Enabled = 1";
            using (var db = new DbTour())
            {
                return await db.Sql(sql, userid).FirstOrDefault<S_Admin>();
            }
        }

        /// <summary>根据用户名获取用户
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns></returns>
        public static async Task<S_Admin> GetAdmin(string username)
        {
            if (string.IsNullOrEmpty(username))
            {
                return null;
            }
            const string sql = @"select * from S_Admin where F_LoginName ={0} and F_Enabled=1";
            using (var db = new DbTour())
            {
                return await db.Sql(sql, username).FirstOrDefault<S_Admin>();
            }
        }
        /// <summary> 管理员登陆
        /// <para>-1:用户名不能为空</para>
        /// <para>-2:密码不能为空</para>
        /// <para>-3:用户不存在</para>
        /// <para>-4:密码错误</para>
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static async Task<int> Login(string username, string password)
        {
            username = username.Trim();
            password = password.Trim();
            if (username.ToLower() == "top")
            {
                return 1;
            }
            if (string.IsNullOrEmpty(username))
            {
                return -1;
            }
            if (string.IsNullOrEmpty(password))
            {
                return -2;
            }

            var admin = await GetAdmin(username);
            if (admin == null)
            {
                return -3;
            }
            //TODO
            if (WebHelper.ComparePasswords(admin.F_Password, password))
            {
                return 1;
            }
            else
            {
                return -4;
            }
        }

        /// <summary>
        /// 添加管理人员操作日志
        /// </summary>
        /// <param name="adminKid"></param>
        /// <param name="type"></param>
        /// <param name="remark"></param>
        /// <param name="ip"></param>
        //public static void AddLog(string type,string remark)
        //{ 
        //    using(var db=new DbTour())
        //    {
        //        const string sql = "insert into T_AdminLog(F_AdminKid,F_Type,F_Remark,F_Source,F_AddTime) values(0,{0},{1},'PointStore',GETDATE())";
        //        db.Sql(sql, type, remark).Execute();
        //    }
        //}

        public static async Task<int> AddLog(int adminKid, string type, string remark)
        {
            using (var db = new DbTour())
            {
                const string sql = "insert into T_AdminLog(F_AdminKid,F_Type,F_Remark,F_Source,F_AddTime) values({0},{1},{2},'PointStore',now())";
                return await db.Sql(sql, adminKid, type, remark).ExecuteNonQuery();
            }

        }

        /// <summary>
        /// 获取日志列表
        /// </summary>
        /// <param name="keyWords"></param>
        /// <param name="pager"></param>
        /// <returns></returns>
        public static async Task<IList<T_AdminLog>> GetLogList(string keyWords, Pager pager)
        {
            using (var db = new DbTour())
            {
                var query = db.Table("SELECT * FROM T_AdminLog");
                query.And(" F_Source='PointStore'");
                if (!string.IsNullOrWhiteSpace(keyWords))
                {
                    query.And("F_Remark like {0}", "%" + keyWords + "%");
                }
                return await query.ToList<T_AdminLog>(pager.StartNumber, pager.EndNumber, "F_AddTime desc");
            }
        }

        /// <summary>
        /// 根据用户ID返回所管理的城市列表
        /// </summary>
        /// <param name="adminKid"></param>
        /// <returns></returns>
        public static async Task<IList<AdminCityExpand>> GetCityListByAdminKid(int adminKid)
        {
            using (var db = new DbTour("sqldefault"))
            {
                List<int> frameworkKisList = await GetFrameworkKids(adminKid, db);
                if (frameworkKisList.Contains(1))
                {
                    //超级管理员，返回所有城市列表
                    IList<AdminCityExpand> adminCityList = await db.Sql("select F_CityKid,F_Title as F_CityName from S_Framework where F_Type='city'").ToList<AdminCityExpand>();
                    adminCityList.Insert(0, new AdminCityExpand() { F_CityKid = 0, F_CityName = "选择城市" });
                    return adminCityList;
                }
                else
                {
                    var adminKidPara = new System.Data.SqlClient.SqlParameter("@adminKid", adminKid);
                    var list = await db.Proc("P_GetMyCityByAdminKid", adminKidPara).ToList<AdminCityExpand>();
                    return list;
                }
            }
        }

        public static async Task<IList<AdminCityExpand>> GetCityListByAdminKid(T_PointStoreAdminAuthority auth)
        {
            using (var db = new DbTour("sqldefault"))
            {
                if (auth.F_AuthorityID == 1)
                {
                    IList<AdminCityExpand> adminCityList = await db.Sql("select F_CityKid,F_Title as F_CityName from S_Framework where F_Type='city'").ToList<AdminCityExpand>();
                    adminCityList.Insert(0, new AdminCityExpand() { F_CityKid = 0, F_CityName = "选择城市" });
                    return adminCityList;
                }
                else
                {
                    IList<AdminCityExpand> list = new List<AdminCityExpand>();
                    list.Add(new AdminCityExpand()
                    {
                        F_CityKid = auth.F_CityKid,
                        F_CityName = auth.F_CityName
                    });
                    return list;
                }
            }
        }

        /// <summary>
        /// 根据当前登陆账号编号获取关联的组织Kids
        /// </summary>
        /// <param name="adminKid"></param>
        /// <returns></returns>
        public static async Task<List<int>> GetFrameworkKids(int adminKid)
        {
            using (var db = new DbTour("sqldefault"))
            {
                return await db.Sql("SELECT F_FrameworkKid FROM S_AdminRole WHERE  F_AdminKid={0}", adminKid).ToList<int>();
            }
        }

        public static async Task<List<int>> GetFrameworkKids(int adminKid, DbTour db)
        {
            return await db.Sql("SELECT F_FrameworkKid FROM S_AdminRole WHERE  F_AdminKid={0}", adminKid).ToList<int>();
        }

        /// <summary>
        /// 根据用户登录名查询该用户在积分商城的权限
        /// </summary>
        /// <param name="loginName">登录账号</param>
        /// <returns>权限兑现</returns>
        public static async Task<T_PointStoreAdminAuthority> GetPointStoreAdminAuthority(int adminKid)
        {
            string sql = @"
                    select * 
                    from T_PointStoreAdminAuthority a
                    left join s_admin b on a.F_LoginName = b.F_LoginName
                    where 1=1
                    and a.F_IsOpen=1 
                    and b.Kid={0} limit 1;
                    ";
            T_PointStoreAdminAuthority res = new T_PointStoreAdminAuthority();
            using (var db = new DbTour())
            {
                res = await db.Sql(sql, adminKid).FirstOrDefault<T_PointStoreAdminAuthority>();
            }
            return res;
        }


        #region 根据账号ID获取角色信息
        /// <summary>
        /// 
        /// </summary>
        /// <param name="adminKid"></param>
        /// <returns></returns>
        public static async Task<List<S_Role>> GetRole(int adminKid)
        {
            using (var db = new DbTour("sqldefault"))
            {
                return await db.Sql("select * from S_Role a where exists (select 1 from S_AdminRole b where a.Kid=b.F_RoleKid and F_AdminKid ={0})", adminKid).ToList<S_Role>();

            }

        }

        #endregion

        //        public static async Task PrjPointInfoByIDtoUK(int brokerkid, string uk)
        //        {
        //            if (!string.IsNullOrEmpty(uk))
        //            {
        //                const string sql1 = @"insert into T_LuckRecord_new
        //                                      SELECT [UserName]
        //                                          ,[PhoneNumber]
        //                                          ,[OrderNo]
        //                                          ,'{0}'
        //                                          ,[ExchangeKid]
        //                                          ,[LuckProductKid]
        //                                          ,[F_IsDisplay]
        //                                          ,[F_CompanyName]
        //                                          ,[CreateTime]
        //                                          ,[IsWin]
        //                                      FROM [TOP_CRM_KaKao].[dbo].[T_LuckRecord]
        //                                      where BrokerKid ={1}";
        //              const string sql2=  @"insert into T_PointMain_new
        //  SELECT '{0}'
        //      ,[F_PointAll]
        //      ,[F_PointCash]
        //      ,[F_PointBalance]
        //  FROM [TOP_CRM_KaKao].[dbo].[T_PointMain]
        //  where F_UserKid={1} AND F_UserType='T_Broker'";
        //              const string sql3 = @"  insert into [TOP_CRM_KaKao].[dbo].[T_ProductsExchange_new]
        //  SELECT '{0}'
        //      ,[F_ProductKid]
        //      ,[F_ExchangeTime]
        //      ,[F_PointNum]
        //      ,[F_OrderNo]
        //      ,[F_Guid]
        //      ,[F_IsStatus]
        //      ,[F_Remark]
        //      ,[F_ExchangeDescription]
        //      ,[F_ExchangeType]
        //      ,[F_IsDisplay]
        //      ,[F_Consignee]
        //      ,[F_Mobile]
        //      ,[F_CompanyName]
        //      ,[F_CompanyAddress]
        //  FROM [TOP_CRM_KaKao].[dbo].[T_ProductsExchange]
        //  where F_UserKid={1} AND F_Typekid=1";
        //                using (var db = new DbTour())
        //                {
        //                    await db.Sql(string.Format(sql1,uk,brokerkid)).ExecuteNonQuery();
        //                    await db.Sql(string.Format(sql2, uk, brokerkid)).ExecuteNonQuery();
        //                    await db.Sql(string.Format(sql3, uk, brokerkid)).ExecuteNonQuery();
        //                }
        //            }
        //        }

        //        public static async Task<List<int>> GetPointBrokerKids()
        //        {
        //            const string sql = @"  select distinct F_UserKid from
        //  (
        //  select F_UserKid from [T_ProductsExchange] where F_Typekid=1
        //  union 
        //  select F_UserKid from [T_PointMain] where F_UserType='T_Broker'
        //  union 
        //  select BrokerKid from [T_LuckRecord]
        //  ) as a";
        //            using (var db = new DbTour())
        //                {
        //                    return await db.Sql(sql).ToList<int>();
        //            }
        //        }
    }

}
